<template>
  <div class="TVChartContainer" :id="containerId" />
</template>

<script>
import api from "./components/api";
import { THEMES, getTheme } from "@/utils/theme";

const getOverrides = () => {
  if (getTheme() === THEMES.dark) {
    return {
      "paneProperties.backgroundType": "solid",
      "paneProperties.background": "#131419",
      "paneProperties.vertGridProperties.color": "#131419",
      "paneProperties.horzGridProperties.color": "#131419",
      "symbolWatermarkProperties.transparency": 90,
      volumePaneSize: "medium",
      MACDPaneSize: "tiny",
      "paneProperties.crossHairProperties.style": 1,
      "mainSeriesProperties.candleStyle.drawBorder": false,
      // "scalesProperties.lineColor": "transparent",
      "scalesProperties.textColor": "rgba(255, 255, 255, 0.3)",
      "mainSeriesProperties.candleStyle.upColor": "#00C076",
      "mainSeriesProperties.candleStyle.borderUpColor": "#00C076",
      "mainSeriesProperties.candleStyle.wickUpColor": "#00C076",
      "mainSeriesProperties.candleStyle.downColor": "#F84960",
      "mainSeriesProperties.candleStyle.borderDownColor": "#F84960",
      "mainSeriesProperties.candleStyle.wickDownColor": "#F84960",
      "mainSeriesProperties.areaStyle.color1": "rgba(48,160,64,0.5)",
      "mainSeriesProperties.areaStyle.color2": "rgba(48,160,64,0.0)",
      "mainSeriesProperties.areaStyle.linecolor": "#f2f2f2",
    };
  }
  return {
    "paneProperties.backgroundType": "solid",
    "paneProperties.background": "#FFFFFF",
    "paneProperties.vertGridProperties.color": "#FFFFFF",
    "paneProperties.horzGridProperties.color": "#FFFFFF",
    "symbolWatermarkProperties.transparency": 90,
    volumePaneSize: "medium",
    MACDPaneSize: "tiny",
    "paneProperties.crossHairProperties.style": 1,
    "mainSeriesProperties.candleStyle.drawBorder": false,
    // "scalesProperties.lineColor": "transparent",
    "scalesProperties.textColor": "rgba(0,0,0,0.2)",
    "mainSeriesProperties.candleStyle.upColor": "#00C076",
    "mainSeriesProperties.candleStyle.borderUpColor": "#00C076",
    "mainSeriesProperties.candleStyle.wickUpColor": "#00C076",
    "mainSeriesProperties.candleStyle.downColor": "#F84960",
    "mainSeriesProperties.candleStyle.borderDownColor": "#F84960",
    "mainSeriesProperties.candleStyle.wickDownColor": "#F84960",
    "mainSeriesProperties.areaStyle.color1": "rgba(48,160,64,0.5)",
    "mainSeriesProperties.areaStyle.color2": "rgba(48,160,64,0.0)",
    "mainSeriesProperties.areaStyle.linecolor": "#f2f2f2",
  };
};
export default {
  name: "TVChartContainer",
  props: {
    symbol: {
      default: "AAPL",
      type: String,
    },
    interval: {
      default: "15",
      type: String,
    },
    containerId: {
      default: "tv_chart_container",
      type: String,
    },
    libraryPath: {
      default: "/charting_library/",
      type: String,
    },
    chartsStorageUrl: {
      default: "https://saveload.tradingview.com",
      type: String,
    },
    chartsStorageApiVersion: {
      default: "1.2",
      type: String,
    },
    clientId: {
      default: "tradingview.com",
      type: String,
    },
    userId: {
      default: "public_user_id",
      type: String,
    },
    fullscreen: {
      default: false,
      type: Boolean,
    },
    autosize: {
      default: true,
      type: Boolean,
    },
  },
  tvWidget: null,
  mounted() {
    const widgetOptions = {
      symbol: this.symbol,
      datafeed: api,
      interval: this.interval,
      container_id: this.containerId,
      library_path: this.libraryPath,
      locale: "en",
      disabled_features: [
        "use_localstorage_for_settings",
        "volume_force_overlay",
        // "left_toolbar",
        // 'widget_logo',
        // 'header_widget_dom_node',
        "header_symbol_search",
        // 'header_chart_type',
        "header_compare",
        "header_undo_redo",
        "header_saveload",
        "header_screenshot",
        // "header_indicators",
        "timeframes_toolbar",
        "header_resolutions",
        // 'header_fullscreen_button',
        "adaptive_logo",
        "pane_context_menu",
        "property_pages",
        // "header_widget",
        "edit_buttons_in_legend",
        "context_menus",
        "control_bar",
        "border_around_the_chart",
        // "create_volume_indicator_by_default",
        // "create_volume_indicator_by_default_once"
      ],
      charts_storage_url: this.chartsStorageUrl,
      charts_storage_api_version: this.chartsStorageApiVersion,
      client_id: this.clientId,
      user_id: this.userId,
      fullscreen: this.fullscreen,
      autosize: this.autosize,
      overrides: getOverrides(),
      theme: getTheme() === THEMES.dark ? "dark" : "light",
      timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
    };
    this.tvWidget = new TradingView.widget(widgetOptions);
    this.tvWidget.headerReady().then(() => {
      this.setChart(this.tvWidget);
    });
    // setTimeout(() => {
    //   if (ready) return;
    //   ready = true;
    //   this.setChart(this.tvWidget);
    // }, 3000);
  },
  methods: {
    setChart(widget) {
      const me = this;
      const chart = widget.chart();
      const btnList = ["line", "1", "5", "15", "30", "60", "1D", "1W", "1M"];
      const btnLabelList = [
        "Line",
        "1m",
        "5m",
        "15m",
        "30m",
        "1H",
        "1D",
        "1W",
        "1M",
      ];
      let timeout = null;
      btnList.forEach((key, i) => {
        const item =
          key === "line"
            ? {
                label: btnLabelList[i],
                resolution: "1",
                chartType: 3,
              }
            : {
                label: btnLabelList[i],
                resolution: key,
              };
        chart.onIntervalChanged().subscribe(null, function (interval, obj) {
          widget.changingInterval = false;
        });
        const button = widget.createButton({
          align: "left",
        });
        button.setAttribute("class", "button");
        button.setAttribute(
          "data-chart-type",
          item.chartType === undefined ? 1 : item.chartType
        );
        button.addEventListener("click", function () {
          clearTimeout(timeout);
          timeout = setTimeout(() => {
            const chartType = +button.getAttribute("data-chart-type");
            if (chart.resolution() !== item.resolution) {
              chart.setResolution(item.resolution);
            }
            if (chart.chartType() !== chartType) {
              chart.setChartType(chartType);
            }
            chart.getAllStudies().map((item) => {
              chart.getStudyById(item.id).setVisible(chartType !== 3);
            });
            updateSelectedIntervalButton(button);
          }, 500);
        });
        button.textContent = item.label;
        if (me.interval == key) {
          button.click();
        }
      });

      function updateSelectedIntervalButton(button) {
        if (widget.selectedIntervalButton) {
          widget.selectedIntervalButton.setAttribute("class", "button");
        }
        button.setAttribute("class", "button selected");
        widget.selectedIntervalButton = button;
      }

      // widget.chart().createStudy("Moving Average", false, true, [30], null, {
      //   "plot.color": "rgb(0, 215, 215)",
      //   "Plot.linewidth": 1,
      // });
      // widget.chart().createStudy("Moving Average", false, true, [60], null, {
      //   "plot.color": "#00C076",
      //   "Plot.linewidth": 1,
      // });
    },
  },
  destroyed() {
    if (this.tvWidget !== null) {
      this.tvWidget.remove();
      this.tvWidget = null;
    }
  },
};
</script>

<style>
.TVChartContainer {
  position: absolute;
  width: 100%;
  height: 100%;
}
</style>
